﻿#ifndef VIDEOPLAYER_H
#define VIDEOPLAYER_H

#include <QThread>
#include <QImage>
#include <QMutex>
#include <QQueue>
#include <QDebug>

#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/core.hpp>
#include <opencv2/videoio.hpp>
#include <opencv2/highgui.hpp>

#include "rtypes.h"

using namespace cv;
using namespace std;
class VideoPlayer : public QThread
{
    Q_OBJECT
public:
    VideoPlayer(QString);
    VideoPlayer(int);

    void setAddr(QString s)
    {
        ISSTR_ADDR = true;
        addr = s.toStdString();
    }

    void setAddr(int i)
    {
        ISSTR_ADDR = false;
        addr_int = i;
    }

    void setRun(bool flag)
    {
        QMutexLocker locker(&mutex);
        IS_RUN = flag;
    }

    int record(const std::string path_name) /* 开始录像 */
    {
        if(!IS_RUN) return ERROR_ThreadNoWork;
        if(!pCap->isOpened()) return ERROR_CapOpen;
        if(pWriter) return WARN_WriteIsWorking;


        pWriter = new VideoWriter;
        double fps = pCap->get(CAP_PROP_FPS);
        if(fps <= 0.0) fps = 25;
        int frame_width = static_cast<int>(pCap->get(CAP_PROP_FRAME_WIDTH));
        int frame_height = static_cast<int>(pCap->get(CAP_PROP_FRAME_HEIGHT));
        if(!pWriter->open(path_name, VideoWriter::fourcc('X','2','6','4'), fps, Size(frame_width, frame_height)))
        {
//            sendErrorCode(ERROR_RecordVideo);
            delete pWriter;
            pWriter = nullptr;
            return ERROR_WirteOpen;
        }

        IS_RECORD = true;
        return ERROR_NO;
    }

    void disrecord(void)   /* 停止录像 */
    {
        IS_RECORD = false;
        pWriter->release();
        delete pWriter;
        pWriter = nullptr;
    }


private:
    string addr;
    int addr_int;
    bool IS_RUN = false;
    QMutex mutex;
    VideoCapture *pCap = nullptr;
    VideoWriter *pWriter = nullptr;
    bool ISSTR_ADDR = false;
    bool IS_RECORD = false;

    QQueue<Mat> recordFrameQueue;

    Q_INVOKABLE void recording(void) /* 正在录像 */
    {
        if(recordFrameQueue.isEmpty()) return;
        for (int i = 0; i < recordFrameQueue.size(); i++) {
            Mat frame = recordFrameQueue.dequeue();
            *pWriter << frame;
        }
    }

signals:
    void sigSendErrorCode(int); /* 发送错误码 */

protected:
    virtual void run() Q_DECL_OVERRIDE;
};

#endif // VIDEOPLAYER_H
